Puzzles from adventofcode.com 2015

Day 4: The Ideal Stocking Stuffer

Santa needs help mining some AdventCoins (very similar to bitcoins) to use as gifts for all the economically forward-thinking little girls and boys.

To do this, he needs to find MD5 hashes which, in hexadecimal, start with at least five zeroes. The input to the MD5 hash is some secret key (your puzzle input, given below) followed by a number in decimal. To mine AdventCoins, you must find Santa the lowest positive number (no leading zeroes: 1, 2, 3, ...) that produces such a hash.

For example:

If your secret key is abcdef, the answer is 609043, because the MD5 hash of abcdef609043 starts with five zeroes (000001dbbfa...), and it is the lowest such number to do so.
If your secret key is pqrstuv, the lowest number it combines with to make an MD5 hash starting with five zeroes is 1048970; that is, the MD5 hash of pqrstuv1048970 looks like 000006136ef....

In [15]:
import hashlib

def valid_adventcoin(key, value, zeroes="00000"):
    return hashlib.md5("{}{}".format(key, value).encode('utf-8')).hexdigest().startswith(zeroes)

def mine_adventcoin(key, zeroes="00000"):
    value = 0
    while not valid_adventcoin(key, value, zeroes=zeroes):
        value += 1
        
    return value

In [16]:
%%time
mine_adventcoin("abcdef")


CPU times: user 3.89 s, sys: 3.98 ms, total: 3.89 s
Wall time: 3.9 s
Out[16]:
609043

In [17]:
%%time
mine_adventcoin("pqrstuv")


CPU times: user 6.61 s, sys: 2.98 ms, total: 6.62 s
Wall time: 6.62 s
Out[17]:
1048970

In [18]:
%%time
mine_adventcoin("iwrupvqb")


CPU times: user 2.2 s, sys: 2 ms, total: 2.2 s
Wall time: 2.21 s
Out[18]:
346386

In [19]:
%%time
mine_adventcoin("iwrupvqb", zeroes="000000")


CPU times: user 1min 2s, sys: 46 ms, total: 1min 2s
Wall time: 1min 2s
Out[19]:
9958218

In [ ]: